from flask import Flask, request, jsonify, redirect
from werkzeug.utils import secure_filename
from PIL import Image
import numpy as np
import os, time, random


token = np.genfromtxt("token", dtype="str")

app = Flask(__name__)


def isImage(f):
    """检测是否图片"""
    try:
        image_pil = Image.open(f)
        image_pil.show()
    except FileExistsError:
        return False
    except Exception as err:
        return False
    else:
        image_pil.close()
        return True


@app.route("/")
def hello_world():
    return "Hello, World!<br> This is a Web for upload static response.<br> headers['authkey'] = 'xxxx'<br> url = '/upload'<br><a href='/web'>try</a>"


@app.route("/web")
def index():
    return """
    <h1>File Upload</h1>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </form>
"""


@app.route("/upload", methods=["POST"])
def upload_file():
    authkey = request.headers.get("authkey")
    if not authkey == token:
        return jsonify({"msg": "认证失败", "code": 1})

    if "file" not in request.files:
        return jsonify({"msg": "查找资源失败", "code": 2})

    file = request.files["file"]
    if file.filename == "":
        return jsonify({"msg": "解析资源名称失败", "code": 3})

    if file:
        filename = secure_filename(file.filename)
        extename = filename.split(".")[-1].lower()
        if not extename in ["jpg", "png", "jpeg", "gif", "bmp", "tiff", "webp"]:
            return jsonify({"msg": "解析资源类型失败", "code": 4})
        thePath = f'/data/{time.strftime("%Y%m%d", time.localtime())}'
        if not os.path.exists(thePath):
            os.makedirs(thePath)
        savename = "".join([str(random.choice(range(10))) for x in range(16)])
        allname = os.path.join(thePath, f"{savename}.{extename}")
        file.save(allname)
        if not isImage(allname):
            os.remove(allname)
            res = {"msg": "解析资源名称失败", "code": 3}
        else:
            res = {"msg": allname, "code": 0}
        return jsonify(res)


    # if __name__ == "__main__":   
    # app.run(host="0.0.0.0", port=8000)
    # app.run()
